<?php

namespace app\admin\controller;

use app\common\model\Quan as QuanModel;
use app\common\model\Jing as JingModel;
use app\common\model\Fu as FuModel;
use app\common\model\MemberQuan as MemberQuanModel;
use app\common\model\UseQuan as UseQuanModel;
use app\common\model\McheckQuan as McheckQuanModel;
use think\Db;
/**
 * 福券控制器
 * Class Quan
 * @package app\admin\controller
 */
class Quan extends Base
{
    /**
     * [index  福券管理列表查看]
     * @param type 1分类 2景区 3福券 4包含景区
     * @return mixed|\think\response\Json
     * @author [C。]
     */
    public function getIndex()
    {
        $data = input('param.');
        $this->getPageAndSize($data);
        $user = $this->user;
        if (!empty($data['type'])){
            $type = $data['type'];
            if($type == 1){
                $model = new QuanModel();
                $map = ['status'=>1];
                try {
                    $count = $model->getTypeCountByCondition($map);//满足条件的总数
                    $allpage = intval(ceil($count / $this->size));//总页数
                    $lists = $model->getTypelist($this->from, $this->size);
                } catch (\Exception $e) {
                    return admin_json(-1,'获取失败');
                }
                writelog('查看福券分类列表',1,$user);

                if (empty($lists))
                    return admin_json(0,'数据为空');

                return admin_json(1, '获取成功',[
                    'count' => $count,//总记录数
                    'allpage' => $allpage,  //总页数
                    'lists' => $lists,  //列表数据
                ]);
            }elseif($type == 2){
                $model = new JingModel();
                $map = [];
                try {
                    $count = $model->getCountByCondition($map);//满足条件的总数
                    $allpage = intval(ceil($count / $this->size));//总页数
                    $lists = $model->getlist($map,$this->from, $this->size);
                } catch (\Exception $e) {
                    return admin_json(-1,'获取失败');
                }
                writelog('查看景区列表',1,$user);
                if (empty($lists))
                    return admin_json(0,'数据为空');

                return admin_json(1, '获取成功',[
                    'count' => $count,//总记录数
                    'allpage' => $allpage,  //总页数
                    'lists' => $lists,  //列表数据
                ]);
            }elseif ($type == 3){
                try {
                    if (is_array($data)) {
                        if(!empty($data['status']) && $data['status'] == 2){
                            $data = $this->status_two($data);
                        }elseif (!empty($data['con']) || !empty($data['start']) || !empty($data['end'])){
                            $data = $this->status_two($data);
                        }else{
                            if(!empty($data['code']))
                                $map['code'] = $data['code'];

                            if(!empty($data['ftype']))
                                $map['type'] = $data['ftype'];

                            if(!empty($data['status']))
                                 $map['status'] = $data['status'];
                            else
                                $map['status'] = ['lt',3];

                            $data = $this->status_one($map);
                        }
                    }

                } catch (\Exception $e) {
                    return admin_json(-1,$e->getMessage());
                }
                writelog('查看福券列表',1,$user);
            }elseif($type == 4){
                $mqmodel = new MemberQuanModel();
                $umodel = new UseQuanModel();
                if($data['ftype'] == '五次'){
                    $map = [];
                    $map['fu_id'] = $data['fid'];
                    $count = $mqmodel->getCountByCondition($map);//满足条件的总数
                    $allpage = intval(ceil($count / $this->size));//总页数
                    $lists = $mqmodel->getlists($map,$this->from, $this->size);
                    foreach($lists as $k=>$v){
                        $map1['member_quan_id'] = $v['member_quan_id'];
                        $result = $umodel->getlist($map1);
                        if(!empty($result)){
                            $lists[$k]['mobile'] = $result['mobile'];
                            $lists[$k]['name'] = $result['name'];
                            $lists[$k]['status'] = $result['status'];
                            $lists[$k]['time'] = $result['time'];
                        }
                    }
                }elseif($data['ftype'] == '二十次'){
                    $jmodel = new JingModel();
                    $map = [];
                    $map['quan_name'] = $data['ftype'];
                    try {
                        $count = $jmodel->getCountByCondition($map);//满足条件的总数
                        $allpage = intval(ceil($count / $this->size));//总页数
                        $lists = $jmodel->getlist($map,$this->from, $this->size,'jing');//所有这个类型的景区
                        $mq = $mqmodel->findData($data['fid'],'fu_id');
                        $map1['member_quan_id'] = $mq['member_quan_id'];
                        $result = $umodel->getAllData($map1,'use_quan_id');
                        foreach($lists as $k=>$v){
                            $lists[$k]['member_quan_id'] = $mq['member_quan_id'];
                            $lists[$k]['member_id'] = $mq['member_id'];
                            $lists[$k]['num'] = $mq['num'];
                            if(!empty($result)){
                                foreach($result as $key=>$value){
                                    if($v['jing'] == $value['jing']){
                                        $lists[$k]['mobile'] = $value['mobile'];
                                        $lists[$k]['name'] = $value['name'];
                                        $lists[$k]['status'] = $value['status'];
                                        $lists[$k]['time'] = $value['time'];
                                    }
                                }
                            }
                        }

                    } catch (\Exception $e) {
                        return admin_json(-1,$e->getMessage());
                    }
                }
                writelog('查看景区列表',1,$user);
                return admin_json(1, '获取成功',[
                    'count' => $count,//总记录数
                    'allpage' => $allpage,  //总页数
                    'lists' => $lists,  //列表数据
                ]);
            }

            if (empty($data['list']) && empty($data['count']))
                return admin_json(0,'数据为空');

            return admin_json(1, '获取成功',$data);
        }else{
            return admin_json(-2,'类型错误');
        }
    }

    /**
     * [index  只有已经兑换]
     * @return mixed|\think\response\Json
     * @author [C。]
     */
    public function status_two($data)
    {
        if(!empty($data['con'])){
            $map['am.username|am.tel'] = ['like', "%" . $data['con'] . "%"];
        }
        if(!empty($data['code'])){
            $map['f.code'] = $data['code'];
        }
        if(!empty($data['ftype'])){
            $map['f.type'] = $data['ftype'];
        }
        if(!empty($data['status'])){
            if($data['status'] == 1)
                return admin_json(0,'数据为空');
            else
                $map['f.status'] = ['lt',3];
        }else{
            $map['f.status'] = ['lt',3];
        }
        if(!empty($data['start']) && !empty($data['end'])){
            $map['mq.addtime'] = ['between',[strtotime($data['start']),strtotime($data['end'])]];
        }
        $model = new FuModel();
        $count = $model->getCountsByCondition($map);//满足条件的总数

        $lists = $model->getlist($map,$this->from, $this->size);
        $allpage = intval(ceil($count / $this->size));//总页数
        return array('count'=>$count,'allpage'=>$allpage,'list'=>$lists);
    }
    /**
     * [index  包括未兑换]
     * @return mixed|\think\response\Json
     * @author [C。]
     */
    public function status_one($map)
    {
        $model = new FuModel();
        $count = $model->getCountByCondition($map);//满足条件的总数
        $allpage = intval(ceil($count / $this->size));//总页数
        $lists = $model->getlists($map,$this->from, $this->size);
        $qmodel = new MemberQuanModel();
        foreach($lists as $k=>$v){
            $map1['fu_id'] = $v['fu_id'];
            $result = $qmodel->getMemberByConditon($map1);
            if(!empty($result)){
                $lists[$k]['tel'] = $result['tel'];
                $lists[$k]['username'] = $result['username'];
                $lists[$k]['addtime'] = date('Y-m-d H:i:s',$result['addtime']);
                $lists[$k]['num'] = $qmodel->getNum($map1);
            }
        }
        return array('count'=>$count,'allpage'=>$allpage,'list'=>$lists);
    }
    /**
     * [index  添加]
     * @return mixed|\think\response\Json
     * @author [C。]
     */
    public function postAdd()
    {
        $model = new QuanModel();
        $param = input('post.');
        $user = $this->user;
        if (!empty($param['type'])){
            $type = $param['type'];
            if($type == 1) {
                try {
                    $model->addType($param);
                } catch (\Exception $e) {
                    return admin_json(-1, '添加失败');
                }
                writelog('添加福券类型'.$param['quan_name'],1,$user);
            }elseif($type == 2){
                $quan = $model->findData($param['qid'],'quan_id');
                $param['quan_name'] = $quan['quan_name'];
                $model = new JingModel();
                try {
                    $model->add($param);
                } catch (\Exception $e) {
                    return admin_json(-1, '添加失败');
                }
                writelog('添加景区'.$param['jing'],1,$user);
            }elseif($type == 3){
                $model = new FuModel();
                $zhang = $param['zhang'];
                $code = 'FS'.date('Ymd',time());

                if($param['quan_id'] != 1){
                    $data['num'] = $param['num'];
                }
                $data['type'] = $param['ftype'];
                $id = '';
                try {
                    for($i=0;$i<$zhang;$i++){
                        $result = $model->getFind($code);
                        if(empty($result)){
                            $data['code'] = $code.'001';
                        }else{
                            $num = substr($result['code'],-3);
                            $num = $num + 1;
                            $num = sprintf('%03s', $num);
                            $data['code'] = $code.$num;
                        }
                        if(!empty($id)){
                            $data['fu_id'] = $id + 1;
                        }
                        $id = $model->add($data);
                    }
                } catch (\Exception $e) {
                    return admin_json(-1, '添加失败');
                }
                writelog('添加福券'.$id,1,$user);
            }
            return admin_json(1, '添加成功');
        }else{
            return admin_json(-2,'类型错误');
        }

    }

    /**
     * [index  修改]
     * @return mixed|\think\response\Json
     * @author [C。]
     */
    public function postEdit()
    {
        $param = input('post.');
        $user = $this->user;
        if (!empty($param['type'])) {
            $type = $param['type'];
            if ($type == 1) {
                $model = new QuanModel();
                try {
                    $model->editType($param);
                } catch (\Exception $e) {
                    return admin_json(-1, '修改失败');
                }

                writelog('修改福券类型'.$param['quan_name'],1,$user);

                return admin_json(1, '修改成功');
            }elseif($type == 2){
                $model = new JingModel();
                try {
                    $model->edit($param);
                } catch (\Exception $e) {
                    return admin_json(-1, '修改失败');
                }

                writelog('修改景区'.$param['jing_id'],1,$user);

                return admin_json(1, '修改成功');
            }elseif($type == 3){
                $mqmodel = new MemberQuanModel();
                try {
                    $mqmodel->editNum($param);
                } catch (\Exception $e) {
                    return admin_json(-1, $e->getMessage());
                }
                writelog('修改使用次数'.$param['member_quan_id'],1,$user);

                return admin_json(1, '修改成功');
            }
        }
    }

    /**
     * [index  删除]
     * @param type 1类型 2景区 3福券
     * @return mixed|\think\response\Json
     * @author [C。]
     */
    public function getDel()
    {
        $data = input('param.');
        $user = $this->user;
        if (!empty($data['type'])) {
            $type = $data['type'];
            if ($type == 1) {
                $model = new QuanModel();
                $id = input('param.quan_id');
                if(empty($id)){
                    return admin_json(2,'id为空');
                }
                $res = $model->deleteFalseData(['quan_id' => $id],['status'=>-1]);
                writelog('删除福券类型--'.$id,1,$user);

                return admin_json(1,'删除福券类型');
            }elseif($type == 2){
                $model = new JingModel();
                $id = input('param.jing_id');
                if(empty($id)){
                    return admin_json(2,'id为空');
                }
                $res = $model->deleteFalseData(['jing_id' => $id],['status'=>-1]);
                writelog('删除景区--'.$id,1,$user);
                return admin_json(1,'删除景区成功');
            }elseif($type == 3){
                $model = new FuModel();
                $id = input('param.fu_id');
                if(empty($id)){
                    return admin_json(2,'id为空');
                }
                $res = $model->deleteFalseData(['fu_id' => $id],['status'=>4]);
                writelog('删除福券--'.$id,1,$user);
                return admin_json(1,'删除福券成功');
            }
        }
    }
    /**
     * [getQuan  所有福券类型]
     * @return mixed|\think\response\Json
     * @author [C。]
     */
    public function getQuan()
    {
        $model = new QuanModel();
        $list = $model->getQuanlist();
        return admin_json(1,'获取福券类型成功',$list);
    }
    /**
     * [getChecklist  福券审核列表]
     * @return mixed|\think\response\Json
     * @author [C。]
     */
    public function getChecklist()
    {
        $param = input('param.');
        $model = new McheckQuanModel();
        $fmodel = new FuModel();
        $this->getPageAndSize($param);
        $map = [];
        $user = $this->user;
        try{
            $count = $model->getCount($map);//满足条件的总数
            $allpage = intval(ceil($count / $this->size));//总页数
            $lists = $model->getList($map,$this->from,$this->size);
            foreach($lists as $k=>$v){
                $fu = $fmodel->findData($v['fu_id'],'fu_id','code,type');
                $lists[$k]['code'] = $fu['code'];
                $lists[$k]['type'] = $fu['type'];
                $lists[$k]['addtime'] = date('Y-m-d',$v['addtime']);
                $lists[$k]['liketime'] = date('Y-m-d',$v['liketime']);
            }
        }catch (\Exception $e) {
            return admin_json(-1, $e->getMessage());
        }
        writelog('查看福券审核列表',1,$user);
        return admin_json(1, '获取成功',[
            'count' => $count,//总记录数
            'allpage' => $allpage,  //总页数
            'lists' => $lists,  //列表数据
        ]);
    }
    /**
     * [getChecklist  福券审核列表]
     * @return mixed|\think\response\Json
     * @author [C。]
     */
    public function postCheck()
    {
        $param = input('param.');
        $model = new McheckQuanModel();
        $qmodel = new MemberQuanModel();
        $user = $this->user;
        try{
            $quan = $model->findData($param['id'],'id','qid,tel,realname');
            $jing = $qmodel->findData($quan['qid'],'member_quan_id','jing,num');

            $data = array(
                'id' => $param['id'],
                'status' => $param['status'],
            );
            if($param['status'] == 1){
                $data['img'] = $param['img'];
                $data['usetime'] = strtotime($param['usetime']);
            }
            if($param['status'] == -1){
                $data['rmk'] = $param['rmk'];
            }

            $id = $model->editData($data);
            if(!empty($id) && $param['status'] == 1){
                if($jing['num'] == 1){
                    $num = $jing['num'] - 1;
                    $qmodel->editNum(['member_quan_id'=>$quan['qid'],'num'=>$num]);
                }
                $a = advice_sendsms($quan['tel'],$jing['jing'],$param['usetime'],$quan['realname']);
            }else{
                $num = $jing['num'] + 1;
                $qmodel->editNum(['member_quan_id'=>$quan['qid'],'num'=>$num]);
                $a = aliyun_sendsms($quan['tel'],$jing['jing'],$param['rmk']);
            }
        }catch (\Exception $e) {
            return admin_json(-1, $e->getMessage());
        }
        writelog('福券审核--'.$param['id'],1,$user);
        return admin_json(1, '审核成功',$a);
    }
    /**
     * [getQuan  导出]
     * @return mixed|\think\response\Json
     * @author [C。]
     */
    public function getExcel()
    {
        $data = input('param.');
        $user = $this->user;
        try {
            if (is_array($data)) {
                if(!empty($data['status']) && $data['status'] == 2){
                    $data = $this->pstatus_two($data);
                }elseif (!empty($data['con']) || !empty($data['start']) || !empty($data['end'])){
                    $data = $this->pstatus_two($data);
                }else{
                    if(!empty($data['code']))
                        $map['code'] = $data['code'];

                    if(!empty($data['ftype']))
                        $map['type'] = $data['ftype'];

                    if(!empty($data['status']))
                        $map['status'] = $data['status'];
                    else
                        $map['status'] = ['lt',3];
                    $data = $this->pstatus_one($map);
                }
            }
            vendor("PHPExcel.PHPExcel");
            $excel = new \PHPExcel();
            //Excel表格式,这里简略写了4列
            $letter = array('A','B','C','D','E','F','G','H');
            //表头数组
            $tableheader = array('ID','兑换状态','福券兑换码','福券类型','剩余次数','兑换账号','兑换用户','最近兑换时间');
            //填充表头信息
            for($i = 0;$i < count($tableheader);$i++) {
                $excel->getActiveSheet()->setCellValue("$letter[$i]1","$tableheader[$i]");
            }
            $excel->getActiveSheet()->getColumnDimension('A')->setWidth(10);
            $excel->getActiveSheet()->getColumnDimension('B')->setWidth(10);
            $excel->getActiveSheet()->getColumnDimension('C')->setWidth(20);
            $excel->getActiveSheet()->getColumnDimension('D')->setWidth(10);
            $excel->getActiveSheet()->getColumnDimension('E')->setWidth(10);
            $excel->getActiveSheet()->getColumnDimension('F')->setWidth(15);
            $excel->getActiveSheet()->getColumnDimension('G')->setWidth(15);
            $excel->getActiveSheet()->getColumnDimension('H')->setWidth(20);
            //填充表格信息
            for ($i = 2;$i <= count($data) + 1;$i++) {
                $j = 0;
                foreach ($data[$i - 2] as $key=>$value) {
                    if($key == 'status'){
                        if($value == 1){
                            $value = '未兑换';
                        }elseif($value == 2){
                            $value = '已兑换';
                        }
                    }
                    if($key == 'addtime'){
                        $value = date('Y-m-d H:i:s',$value);
                    }
                    $excel->getActiveSheet()->setCellValue("$letter[$j]$i","$value");
                    $j++;
                }
            }

            //创建Excel输入对象
            $write = new \PHPExcel_Writer_Excel5($excel);
            header("Pragma: public");
            header("Expires: 0");
            header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
            header("Content-Type:application/force-download");
            header("Content-Type:application/vnd.ms-execl");
            header("Content-Type:application/octet-stream");
            header("Content-Type:application/download");;
            header('Content-Disposition:attachment;filename="福券使用状况表.xls"');
            header("Content-Transfer-Encoding:binary");
            $write->save('php://output');
        } catch (\Exception $e) {
            return admin_json(-1,$e->getMessage());
        }
        writelog('福券导出excel',1,$user);
        return admin_json(1,'导出成功');
    }
    /**
     * [pstatus_two  只有已经兑换]
     * @return mixed|\think\response\Json
     * @author [C。]
     */
    public function pstatus_two($data)
    {
        if(!empty($data['con'])){
            $map['am.username|am.tel'] = ['like', "%" . $data['con'] . "%"];
        }
        if(!empty($data['code'])){
            $map['f.code'] = $data['code'];
        }
        if(!empty($data['ftype'])){
            $map['f.type'] = $data['ftype'];
        }
        if(!empty($data['status'])){
            if($data['status'] == 1)
                return admin_json(0,'数据为空');
            else
                $map['f.status'] = ['lt',3];
        }else{
            $map['f.status'] = ['lt',3];
        }
        if(!empty($data['start']) && !empty($data['end'])){
            $map['mq.addtime'] = ['between',[strtotime($data['start']),strtotime($data['end'])]];
        }
        $model = new FuModel();

        $lists = $model->getlist($map);

        return $lists;
    }
    /**
     * [pstatus_one  包括未兑换]
     * @return mixed|\think\response\Json
     * @author [C。]
     */
    public function pstatus_one($map)
    {
        $model = new FuModel();
        $lists = $model->getlists($map);
        $qmodel = new MemberQuanModel();
        foreach($lists as $k=>$v){
            $map1['fu_id'] = $v['fu_id'];
            $result = $qmodel->getMemberByConditon($map1);
            if(!empty($result)){
                $lists[$k]['tel'] = $result['tel'];
                $lists[$k]['username'] = $result['username'];
                $lists[$k]['addtime'] = $result['addtime'];
                $lists[$k]['num'] = $qmodel->getNum($map1);
            }
        }
        return $lists;
    }
    /**
     * [getUplExcel  导入]
     * @return mixed|\think\response\Json
     * @author [C。]
     */
    public function postUplExcel()
    {
        $model = new FuModel();
        $user = $this->user;
        vendor("PHPExcel.PHPExcel");

        if (!empty($_FILES['file']['name'])) {
            $fileName = $_FILES['file']['name'];    //得到文件全名
            $dotArray = explode('.', $fileName);    //把文件名安.区分，拆分成数组
            $type = end($dotArray);
            if ($type != "xls" && $type != "xlsx") {
                return admin_json(0,'不是Excel文件，请重新上传!');
            }
            //取数组最后一个元素，得到文件类型
            $uploaddir = "excel/" . date("Y-m-d") . '/';//设置文件保存目录 注意包含

            if (!file_exists($uploaddir)) {
                mkdir($uploaddir, 0755, true);
            }

            $path = $uploaddir . md5(uniqid(rand())) . '.' . $type; //产生随机文件名
            //$path = "images/".$fileName; //客户端上传的文件名；
            //下面必须是tmp_name 因为是从临时文件夹中移动
            move_uploaded_file($_FILES['file']['tmp_name'], $path); //从服务器临时文件拷贝到相应的文件夹下

            $file_path = $path;
            if (!file_exists($path)) {
                $ret['res'] = "0";
                $ret['msg'] = "上传文件丢失!" . $_FILES['excel']['error'];
                return json_encode($ret);
            }

            //文件的扩展名
            $ext = strtolower(pathinfo($path, PATHINFO_EXTENSION));
            if ($ext == 'xlsx') {
                $objReader = \PHPExcel_IOFactory::createReader('Excel2007');
                $objPHPExcel = $objReader->load($file_path, 'utf-8');
            } elseif ($ext == 'xls') {
                $objReader = \PHPExcel_IOFactory::createReader('Excel5');
                $objPHPExcel = $objReader->load($file_path, 'utf-8');
            }

            $sheet = $objPHPExcel->getSheet(0);
            $highestRow = $sheet->getHighestRow(); // 取得总行数
            $highestColumn = $sheet->getHighestColumn(); // 取得总列数
            $i = 0;

            for ($j = 2; $j < $highestRow; $j++) {
                $data['status'] = (string)$objPHPExcel->getActiveSheet()->getCell("A$j")->getValue();//需要导入的status
                $data['code'] = (string)$objPHPExcel->getActiveSheet()->getCell("B$j")->getValue();   //需要导入的code
                $data['type'] = (string)$objPHPExcel->getActiveSheet()->getCell("C$j")->getValue(); //需要导入的type
                if($data['status'] == '未兑换') {
                    $data['status'] = 1;
                }elseif($data['status'] == '已兑换') {
                    $data['status'] = 2;
                }else{
                    $data['status'] = 3;
                }

                $code_s = $model->findData($data['code'],'code');

                if($code_s)
                {
                    continue;
                }

                if($data['type'] == '五次'){
                    $data['num'] = 5;
                }else{
                    $data['num'] = 20;
                }

                $res = Db::name('fu')->insert($data);//这里就是我的数据库添加操作定义的一个方法啦,对应替换为自己的

                if ($res) {
                    $i++;
                }
            }
            if($i>0) {
                writelog('福券导入',1,$user);
                return admin_json(1,'导入成功');
            } else {
                return admin_json(-1,'导入失败');
            }
        } else {
            return admin_json(-2,'上传文件失败');
        }
    }
}